<template>
  <div class="event-info">
    <el-form :model="ruleForm" :rules="rules" ref="UserForm" label-positionId="150px" label-suffix="：">
      <div class="event-content">
        <el-form-item label="所属广告位" prop="positionId">
          <div class="cont-input">
            <el-select v-model="ruleForm.positionId" placeholder="请选择">
              <el-option v-for="item in sortData" :key="item.id" :label="item.positionName" :value="item.id"></el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="广告标题" prop="title">
          <div class="cont-input">
            <el-input v-model="ruleForm.title" placeholder="请输入广告标题"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="信息图片" prop="fileSrc">
          <UpLoad 
            v-model="ruleForm.fileSrc" 
            :limit="fileSrcProp.limit"
            :editId="editId"
            :type="fileSrcProp.type"
            :filelist="filelist"
            @geturl="getPictureUrl"
          />
        </el-form-item>
        <el-form-item label="广告有效期至" prop="validDate">
          <div class="cont-input">
            <el-date-picker
              v-model="ruleForm.validDate"
              type="date"
              placeholder="选择日期">
            </el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="目标页面链接" prop="linkUrl">
          <div class="cont-input">
            <el-input v-model="ruleForm.linkUrl" placeholder="请输入广告链接的页面地址"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="isActivity">
          <div class="cont-input">
            <el-switch
              v-model="ruleForm.isActivity"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <div class="cont-input">
            <el-input v-model="ruleForm.remark" type="textarea" placeholder="请输入备注"></el-input>
          </div>
        </el-form-item>
      </div>
      <div class="cont-footer">
        <el-button @click.native="cancelPop">取消</el-button>
        <template v-if="commonTabInfo.text === '新增'">
          <el-button type="primary" @click.native="addAdvertiseInfoEvent">保存</el-button>
        </template>
        <template v-else-if="commonTabInfo.text === '编辑'">
          <el-button type="primary" @click.native="editAdvertiseInfoEvent">保存编辑</el-button>
        </template>
      </div>
    </el-form>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { AddOrUpdateAdvertiseInfo, GetAdvertiseInfoSingle, GetAdvertisePosiTable, DeletePic } from '@/api/requestConfig'
  import { formatTime } from '@/utils/index'
  import UpLoad from '@/components/Upload'
  export default {
    name: 'AdvertiseInfo',
    data() {
      return {
        sortData: [],
        editId: 0, // 编辑Id
        filelist: [], // 编辑图片
        fileSrcProp: {
          type: 3, // 消息发布1；合作伙伴2；广告3；
          limit: 1
        }, // 图片上传组件参数
        ruleForm: {
          isActivity: 1,
          title: '',
          linkUrl: '',
          positionId: '',
          remark: '',
          fileSrc: '',
          validDate: ''
        },
        rules: {
          positionId: [
            { required: true, message: '请选择所属广告位', trigger: 'change' }
          ],
          title: [
            { required: true, message: '请输入广告位内容名称', trigger: 'blur' }
          ],
          fileSrc: [
            { required: true, message: '请选择广告图', trigger: 'change' }
          ]
        },
        editData: {},
        addFlag: true
      }
    },
    computed: {
      ...mapGetters([
        'commonTabInfo'
      ])
    },
    components: {
      UpLoad
    },
    created() {
      // 获取菜单数据
      var needData = {
        curPage: 1,
        pageSize: 1000
      }
      GetAdvertisePosiTable(needData).then(res => {
        if (res.data) {
          this.sortData = res.data
        }
      }).then(() => {
        if (this.commonTabInfo.text === '编辑') {
          this.editId = this.commonTabInfo.custom.id
          GetAdvertiseInfoSingle(this.editId).then(res => {
            if (res.data) {
              const resData = res.data
              this.editData = resData
              if (this.editData) {
                for (var key in this.ruleForm) {
                  if (key === 'validDate' && this.editData[key]) {
                    this.ruleForm[key] = new Date(this.editData[key])
                  } else {
                    this.ruleForm[key] = this.editData[key]
                  }
                }
                // 渲染图片
                if (this.ruleForm.fileSrc) {
                  var resultList = []
                  var srcArr = this.ruleForm.fileSrc.split(',')
                  for (var i = 0; i < srcArr.length; i++) {
                    var obj = {}
                    obj.name = srcArr[i]
                    obj.url = srcArr[i]
                    resultList.push(obj)
                  }
                  this.filelist = resultList
                  this.ruleForm.fileSrc = resultList
                }
              }
            }
          })
        }
      })
    },
    methods: {
      // tabs操作
      eventTab(text, tabsName, custom) {
        this.$store.dispatch('handleTabInfo', {
          text: text,
          tabsName: tabsName,
          custom: custom
        })
      },
      // 取消
      cancelPop() {
        // 新增时如果上传了图片，需删除
        var self = this
        if (this.commonTabInfo.text === '新增') {
          var picUrl = ''
          if (self.ruleForm.fileSrc.length > 0) {
            for (var i = 0; i < self.ruleForm.fileSrc.length; i++) {
              if (i === 0) {
                picUrl = picUrl + self.ruleForm.fileSrc[i].response.data
              } else {
                picUrl = picUrl + ',' + self.ruleForm.fileSrc[i].response.data
              }
            }
          }
          var needData = {}
          needData.picName = picUrl
          needData.type = this.fileSrcProp.type
          DeletePic(needData).then(res => {
            console.log(res)
          })
        }
        this.eventTab('', 'first')
      },
      // 获取图片上传路径
      getPictureUrl(fileList) {
        this.ruleForm.fileSrc = fileList
      },
      // 新增
      addAdvertiseInfoEvent() {
        console.log(this.ruleForm.validDate)
        var self = this
        if (!this.addFlag) {
          return
        }
        this.$refs.UserForm.validate(function(valid) {
          if (valid) {
            var needData = {}
            needData.title = self.ruleForm.title
            needData.linkUrl = self.ruleForm.linkUrl
            needData.remark = self.ruleForm.remark
            needData.isActivity = self.ruleForm.isActivity
            needData.positionId = self.ruleForm.positionId
            if (self.ruleForm.validDate) {
              needData.validDate = formatTime(self.ruleForm.validDate) + 'T23:59:59'
            }
            var picUrl = ''
            if (self.ruleForm.fileSrc.length > 0) {
              for (var i = 0; i < self.ruleForm.fileSrc.length; i++) {
                var thisUrl = ''
                if (self.ruleForm.fileSrc[i].response && self.ruleForm.fileSrc[i].response.data) {
                  thisUrl = self.ruleForm.fileSrc[i].response.data
                } else {
                  thisUrl = self.ruleForm.fileSrc[i].url
                }
                if (i === 0) {
                  picUrl = picUrl + thisUrl
                } else {
                  picUrl = picUrl + ',' + thisUrl
                }
              }
            }
            needData.fileSrc = picUrl
            self.addFlag = false
            AddOrUpdateAdvertiseInfo(needData).then(res => {
              if (res.code === 200) {
                self.$message.success(res.message)
                setTimeout(function() {
                  self.eventTab('refresh', 'first', 'advertiseInfo')
                }, 500)
              } else {
                self.$message.error(res.message)
              }
            }).catch(error => {
              console.log(error)
            })
          } else {
            return
          }
        })
        setTimeout(function() {
          self.addFlag = true
        }, 3000)
      },
      // 编辑
      editAdvertiseInfoEvent() {
        var self = this
        if (!this.addFlag) {
          return
        }
        this.$refs.UserForm.validate(function(valid) {
          if (valid) {
            var needData = {}
            needData.id = self.editData.id
            needData.title = self.ruleForm.title
            needData.linkUrl = self.ruleForm.linkUrl
            needData.remark = self.ruleForm.remark
            needData.isActivity = self.ruleForm.isActivity
            needData.positionId = self.ruleForm.positionId
            if (self.ruleForm.validDate) {
              needData.validDate = formatTime(self.ruleForm.validDate) + 'T23:59:59'
            }
            var picUrl = ''
            console.log(self.ruleForm.fileSrc)
            if (self.ruleForm.fileSrc.length > 0) {
              for (var i = 0; i < self.ruleForm.fileSrc.length; i++) {
                var thisUrl = ''
                if (self.ruleForm.fileSrc[i].response && self.ruleForm.fileSrc[i].response.data) {
                  thisUrl = self.ruleForm.fileSrc[i].response.data
                } else {
                  thisUrl = self.ruleForm.fileSrc[i].url
                }
                if (i === 0) {
                  picUrl = picUrl + thisUrl
                } else {
                  picUrl = picUrl + ',' + thisUrl
                }
              }
            }
            needData.fileSrc = picUrl
            self.addFlag = false
            AddOrUpdateAdvertiseInfo(needData).then(res => {
              if (res.code === 200) {
                self.$message.success(res.message)
                setTimeout(function() {
                  self.eventTab('update', 'first', 'advertiseInfo')
                }, 500)
              } else {
                self.$message.error(res.message)
              }
            }).catch(error => {
              console.log(error)
            })
          } else {
            return
          }
        })
        setTimeout(function() {
          self.addFlag = true
        }, 3000)
      }
    }
  }
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  @import "src/styles/info.scss";
</style>
